﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Security;
using SharingCenter.Web.Classes.Groups;
using SharingCenter.Web.Classes.enums;

namespace SharingCenter.Web.Classes
{
    public partial class PageBase : System.Web.UI.Page
    {
        //static CustomizedProfile _pro = null;
        //protected static WebsiteDataContext WebsiteDataContext = WebsiteDataContext.Instance;
        protected scDataContext dataContext = null;

        protected void SetNav(string navName)
        {
            ((ITemplateManupulation)Page.Master).SetNavName(navName);
        }

        protected void SetMasterSiteMapOverride(bool ifOverride)
        {
            ((ITemplateManupulation)Page.Master).SetOverrideSiteMapPath(ifOverride);
        }


        //protected void HideMasterRightBar(bool hide)
        //{
        //    ((ITemplateManupulation)Page.Master).HideRightBarContactList = hide;
        //}

        protected PageBase()
        {
            //if (dataContext == null)
            //{
            //    dataContext = new scDataContext();
            //}
            //this.Unload += new EventHandler(PageBase_Unload);
            dataContext = ServiceLayer.MyDataContextHelper.CurrentContext;
        }

        void PageBase_Unload(object sender, EventArgs e)
        {
            try
            {
                dataContext.Dispose();
                dataContext = null;
            }
            catch { }
        }

        

        public static WebProfile Profile
        {
            get { return WebProfile.Current; }
        }

        protected void RefreshPage()
        {
            Response.Redirect(Request.Url.ToString(), true);
        }

        public virtual void RedirectToDefaultPage()
        {
            Response.Redirect("~/");
        }

        protected void RefreshPage(bool addHashCode)
        {
            Response.Redirect(Request.Url.AbsolutePath + "?" + Utility.AddHashToQueryString(Request.QueryString));
        }

        //protected WebProfile WebProfile
        //{
        //    get { return new WebProfile(Context.Profile); }
        //}

        /// <summary>
        /// Returns a clipped area of an image.
        /// </summary>
        protected Image ClipImage(Image originalImg, Rectangle clipRectangle)
        {
            Bitmap clippedBmp = new Bitmap(clipRectangle.Width, clipRectangle.Height);

            using (Graphics g = Graphics.FromImage(clippedBmp))
            {

                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.DrawImage(originalImg,
                            new Rectangle(0, 0, clipRectangle.Width, clipRectangle.Height),
                            clipRectangle,
                            GraphicsUnit.Pixel);
            }

            //Bitmap b = new Bitmap((Image)clippedBmp, 150, 150);
            
            return (Image)clippedBmp;
        }

        protected void ResizeFromStream(string ImageSavePath, int MaxSideSize, Stream Buffer)
        {
            int intNewWidth = 0;
            int intNewHeight = 0;
            using (Image imgInput = Image.FromStream(Buffer))
            {
                //Determine image format
                ImageFormat fmtImageFormat = imgInput.RawFormat;

                //get image original width and height
                int intOldWidth = imgInput.Width;
                int intOldHeight = imgInput.Height;

                //determine if landscape or portrait
                int intMaxSide;

                if (intOldWidth >= intOldHeight)
                {
                    intMaxSide = intOldWidth;
                }
                else
                {
                    intMaxSide = intOldHeight;
                }


                if (intMaxSide > MaxSideSize)
                {
                    //set new width and height
                    double dblCoef = MaxSideSize / (double)intMaxSide;
                    intNewWidth = Convert.ToInt32(dblCoef * intOldWidth);
                    intNewHeight = Convert.ToInt32(dblCoef * intOldHeight);
                }
                else
                {
                    intNewWidth = intOldWidth;
                    intNewHeight = intOldHeight;
                }

                //create new bitmap

                using (Bitmap bmpResized = new Bitmap(intNewWidth, intNewHeight))
                {
                    using (Graphics g = Graphics.FromImage(bmpResized))
                    {
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.FillRectangle(Brushes.White, 0, 0, intNewWidth, intNewHeight);
                        g.DrawImage(imgInput, 0, 0, intNewWidth, intNewHeight);
                    }

                    bmpResized.Save(ImageSavePath, fmtImageFormat);
                }
            }
        }

        protected void SetTopMostMessage(string text, bool pageUpdated)
        {
            TopMostMessageText = text;
            PageUpdated = pageUpdated;
        }

        public static string TopMostMessageText
        {
            get
            {
                return HttpContext.Current.Session["TOP_MOST_MESSAGE"].ToString();
            }
            set
            {
                HttpContext.Current.Session["TOP_MOST_MESSAGE"] = value;
            }
        }

        public static bool PageUpdated
        {
            get
            {
                try
                {
                    return Convert.ToBoolean(HttpContext.Current.Session["PAGE_UPDATED"]);
                }
                catch
                {
                    return false;
                }
            }

            set
            {
                HttpContext.Current.Session["PAGE_UPDATED"] = value;
            }

        }

        private static aspnet_Membership _me = null;

        public static aspnet_Membership Me
        {
            get
            {
                try
                {
                    if (_me == null)
                    {
                        using (scDataContext cxt = new scDataContext())
                        {
                            _me = cxt.aspnet_Memberships.Single(d => d.UserId == Profile.UserId);
                        }
                    }

                    return _me;
                }
                catch { return null; }
            }
        }

        public static void RaiseError(Exception ex, string messageToShow)
        {
            HttpContext.Current.Session[WebConsts.SK_MODAL_MESSAGE] =
                new ModalMessageItem(messageToShow);
        }

        public void AuthenticationRequired(string extraQueryString)
        {
            if (!User.Identity.IsAuthenticated)
            {
                FormsAuthentication.RedirectToLoginPage(extraQueryString);
                Response.Flush();
                return;
                //Response.Redirect(FormsAuthentication.LoginUrl);
            }
        }

        public bool IsUserNameAdmin(string username)
        {
            return username.ToLower().StartsWith(WebConsts.ADMIN_USERNAME_PREFIX.ToLower());
        }
    }

    public partial class AdminPageBase : PageBase
    {
        public override void RedirectToDefaultPage()
        {
            Response.Redirect("~/Admin", true);
        }
    }

    public partial class EventPageBase : PageBase 
    {
        public EventPageBase()
            : base()
        {
            this.InitComplete += new EventHandler(EventPageBase_InitComplete);
        }

        void EventPageBase_InitComplete(object sender, EventArgs e)
        {
            SetNav("events");
        }
    }

    public partial class HomePageBase : PageBase
    {
        public HomePageBase()
            : base()
        {
            this.InitComplete += new EventHandler(EventPageBase_InitComplete);
        }

        void EventPageBase_InitComplete(object sender, EventArgs e)
        {
            SetNav("home");
        }
    }

    public partial class MessagePageBase : PageBase
    {
        public enum XEntity
        {
            Value,
            Attribute
        }

        public MessagePageBase()
            : base()
        {
            //this.InitComplete += new EventHandler(EventPageBase_InitComplete);
        }

       
    }

    public partial class LearningPageBase : PageBase
    {
        public LearningPageBase()
            : base()
        {
            this.InitComplete += new EventHandler(EventPageBase_InitComplete);
        }

        void EventPageBase_InitComplete(object sender, EventArgs e)
        {
            SetNav("learning");
        }

        public override void RedirectToDefaultPage()
        {
            Response.Redirect("~/Mod/Learning");
        }
    }

    public partial class GroupsPageBase : PageBase
    {
        protected Guid groupId;
        protected Sc_GroupMember member;
        protected Sc_Group group;
        protected string appName = "Groups";
        protected string appFolder = "Groups";
        private bool parsed = false;

        public GroupsPageBase()
            : base()
        {
            //this.InitComplete += new EventHandler(GroupsPageBase_InitComplete);

        }

        //protected void Page_Init(object sender, EventArgs e)
        //{
        //    Response.Write("hello");
        //    ParseGroupIdFromQueryString();
        //    SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(SiteMap_SiteMapResolve);
        //}

        void Page_InitComplete(object sender, EventArgs e)
        {
            SetNav("groups");
        }

        public override void RedirectToDefaultPage()
        {
            Response.Redirect("~/Mod/Groups");
        }

        protected void HasRights(Guid groupId, Guid userId)
        {
            bool redirect = false;
            using (scDataContext cxt = new scDataContext())
            {
                if (!Convert.ToBoolean(cxt.UserHasGroupAccessRight(groupId, userId)))
                {
                    redirect = true;
                }
            }

            this.IsDisabled(groupId);

            if (redirect)
            {
                RedirectToNoRightsPage();
            }
        }

        protected void HasRights(Guid groupId, Guid userId, bool memberOnly)
        {
            bool redirect = false;
            using (scDataContext cxt = new scDataContext())
            {
                if (!Convert.ToBoolean(cxt.UserHasGroupAccessRight(groupId, userId)))
                {
                    redirect = true;
                }

                if (memberOnly && member == null)
                {
                    redirect = true;
                }

                IsDisabled(groupId);
            }

            if (redirect)
            {
                RedirectToNoRightsPage();
            }
        }

        protected void IsDisabled(Guid groupId)
        {
            if (null == this.group)
            {
                this.group = GroupOperations.GetGroupByGroupId(this.groupId);
            }
            if (!this.group.Approved)
            {
                Response.Redirect("~/Mod/Groups/Disabled.aspx", true);
            }
        }

        protected void HasRights(Guid groupId, Guid userId, out bool hasRights)
        {
            using (scDataContext cxt = new scDataContext())
            {
                hasRights = Convert.ToBoolean(cxt.UserHasGroupAccessRight(groupId, userId));
            }
        }

        public void RedirecToGroupHomePage(Guid groupId)
        {
            Response.Redirect("~/Mod/Groups/ViewGroup.aspx?id=" + groupId);
        }

        public void RedirectToNoRightsPage()
        {
            Response.Redirect("~/Mod/Groups/NoRights.aspx");
        }

        public void RedirectToPostPage(Guid threadId, bool updateVisitCount)
        {
            string r = string.Format("~/Mod/Groups/Posts/Posts.aspx?t={0}&id={1}", threadId, Request.QueryString["id"]);
            if (updateVisitCount)
            {
                r += @"&u=" + Guid.NewGuid();
            }
            Response.Redirect(r);
        }

        protected void ParseGroupIdFromQueryString()
        {
            if (!parsed)
            {
                try
                {
                    groupId = new Guid(Request.QueryString["id"]);
                    group = GroupOperations.GetGroupByGroupId(groupId);
                    member = GroupOperations.GetGroupMember(groupId, Profile.UserId);
                }
                catch { }
                parsed = true;
            }
        }

        protected void IsAdminOrRedirect(Sc_GroupMember m)
        {
            if (m == null || m.AdminRole != GroupRole.GroupAdmin && m.AdminRole != GroupRole.Owner)
            {
                RedirectToNoRightsPage();
            }
        }
    }

    public partial class TalksPageBase : PageBase
    {
        protected string appName = "Talks";
        protected string appFolder = "Talks";

        public TalksPageBase()
            : base()
        {
            this.InitComplete += new EventHandler(EventPageBase_InitComplete);
        }

        void EventPageBase_InitComplete(object sender, EventArgs e)
        {
            SetNav("talks");
        }

        public void RedirectToThreadPage(Guid category)
        {
            Response.Redirect(string.Format("Threads.aspx?c={0}", category));
        }

        public void RedirectToPostPage(Guid threadId, bool updateVisitCount)
        {
            string r = string.Format("Thread.aspx?t={0}", threadId);
            if(updateVisitCount)
            {
                r += @"&u="+Guid.NewGuid();
            }
            Response.Redirect(r, true);

            
        }
    }

    public partial class ContactPageBase : PageBase
    {
    }


}
